<template>
  <div>
    <div class="signature-container">
      <el-row>
        <el-color-picker
          v-model="signatureOptions.penColor"
          @change="changeColor"
        ></el-color-picker>
      </el-row>
      <!-- 签名区域 -->
      <vue-signature-pad
        ref="signaturePad"
        :options="signatureOptions"
        class="signature-pad"
      />
      <!-- 操作按钮 -->
      <div class="signature-actions">
        <el-button
          type="info"
          icon="el-icon-delete"
          @click="clearSignature"
          plain
          >清除</el-button
        >
        <el-button type="warning" icon="el-icon-refresh" @click="undoSignature"
          >撤销</el-button
        >
        <el-button type="primary" icon="el-icon-finished" @click="saveSignature"
          >确认签名无误，下一步</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import VueSignaturePad from 'vue-signature-pad';

export default {
  components: {
    VueSignaturePad
  },
  props: {
    formFiled: {
      type: String,
      default: "",
    }
  },
  data() {
    return {
      signatureVisibled: false,
      // 签名配置
      signatureOptions: {
        penColor: '#EB0D0D', // 笔触颜色
        backgroundColor: '#f8f9fa', // 背景色
        minWidth: 1, // 最小笔触宽度
        maxWidth: 1.5, // 最大笔触宽度
        dotSize: 2 // 点的大小
      }
    };
  },
  mounted() {
    // 初始化时清空签名板
    this.$nextTick(() => {
      this.clearSignature();
    });
  },
  methods: {
    show() {
      this.signatureVisibled = true;
      this.clearSignature();//每次打开都先清空一遍
    },
    handleClose() {
      this.$emit("closeSignature");
    },
    changeColor(data) {
      console.log("changeColor", data);
      this.updateStyle(data); // 将 data 传递给 updateStyle
    },
    updateStyle(newColor) {
      if (newColor) {
        console.log(1);
        this.signatureOptions.penColor = newColor;

        // 重新初始化签名板以应用新颜色
        // 这是解决颜色不更新的关键
        if (this.$refs.signaturePad) {
          console.log(2);
          // 保存当前的签名数据（如果有）
          const saveData = this.$refs.signaturePad.saveSignature();
          console.log("saveData", saveData);
          // 清除并重新设置
          this.$refs.signaturePad.clearSignature();

          // 如果之前有签名，尝试恢复
          if (saveData && !saveData.isEmpty) {
            console.log(3);
            // 给一点延迟确保画布已更新
            setTimeout(() => {
              this.$refs.signaturePad.fromData(saveData.data);
            }, 100);
          }
        }
      }
    },
    // 清除签名
    clearSignature() {
      if (this.$refs.signaturePad) {
        this.$refs.signaturePad.clearSignature();
        this.signatureImage = null;
      }
    },
    // 保存签名（PNG格式）
    saveSignature() {
      if (this.$refs.signaturePad) {
        const res = this.$refs.signaturePad.saveSignature();
        console.log("签名数据", JSON.stringify(res));
        if (res && !res.isEmpty) {
          this.$emit("save", { signatureBase64: res.data, formFiled: this.formFiled });
          this.signatureVisibled = false;
        } else {
          this.$alert("请先完成签名")
        }
      }
    },
    downloadSignature() {
      const res = this.$refs.signaturePad.saveSignature();
      console.log("签名数据", JSON.stringify(res));
      if (res && !res.isEmpty) {
        // 2. 转换为Blob
        const blob = this.base64ToBlob(res.data);

        // 3. 此时可直接使用Blob（示例：上传到服务器或保存为本地文件）
        console.log('Blob图片对象:', blob);

        // 示例2：下载为本地图片
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '签名.png';
        a.click();
        URL.revokeObjectURL(url); // 释放URL对象
      } else {
        this.$alert("请先完成签名")
      }
    },
    // 核心：将Base64转换为Blob
    base64ToBlob(base64Data) {
      const byteString = atob(base64Data.split(',')[1]); // 去掉DataURL前缀
      const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    /**
     * 生成GUID并添加.png格式的附件名称
     * @returns {string} 格式如 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.png 的字符串
     */
    create_uuid_fileName() {
      // 生成GUID的核心逻辑
      const guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });

      // 拼接.png后缀并返回
      return `${guid}.png`;
    },
    // 撤销上一步
    undoSignature() {
      if (this.$refs.signaturePad) {
        this.$refs.signaturePad.undoSignature();
      }
    }
  }
};
</script>

<style scoped>
.signature-container {
  width: 800px;
  height: 461.89px;
  padding: 0 10px;
  margin: 0 auto;
}

.signature-pad {
  width: 100%;
  height: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 20px;
}

.signature-actions {
  text-align: center;
}

.signature-preview img {
  max-width: 100%;
  border: 1px dashed #ccc;
  padding: 10px;
}
</style>
